package edu.nf.db.util.converter;
import edu.nf.db.util.TypeConverter;

import java.sql.Time;
import java.sql.Timestamp;
import java.time.*;
import java.util.Date;

/**
 * @Author lzp
 * @Date 2024-05-09
 * 将数据库不同类型的日期类型统一转换为java.util.Date 或者是它的子类
 */
public class DateConverter implements TypeConverter {
    @Override
    public boolean supports(Class<?> type) {
        //获取type全限定类名
        String typrName = type.getName();
        return switch (typrName){
            case "java.util.Date",
                    "java.sql.Timestamp",
                    "java.sql.Date",
                    "java.sql.Time" -> true;
            default -> false;
        };

    }

    @Override
    public Object convert(Class<?> fieldType, Object value) {
        String typeName = fieldType.getName();
        long time = getTime(value);
        return switch (typeName){
            case "java.util.Date" -> new Date(time);
            case "java.sql.Date" -> new java.sql.Date(time);
            case "java.sql.Timestamp" -> new Timestamp(time);
            case "java.util.Time" -> new Time(time);
            default -> null;
        };
    }

    /**
     * 将日期都变成long的类型
     * @param vaule
     * @return
     */
    private long getTime(Object vaule){
//        if (vaule instanceof Date){
//            Date date = (Date) vaule;
//            date.getTime();
//        }
        return switch (vaule){
            case Date date -> date.getTime();
            case LocalDateTime localDateTime -> localDateTimeToDate(localDateTime).getTime();
            case LocalDate localDate -> localDateToDate(localDate).getTime();
            case LocalTime localTime -> localTimeToDate(localTime).getTime();
            default -> throw new RuntimeException("unable to convert "+vaule+ " to Date");
        };
    }

    /**
     * 将 localDateTime 转换为 Date
     */
    private Date localDateTimeToDate(LocalDateTime localDateTime){
        ZoneId zoneId = ZoneId.systemDefault();
        Instant instant = localDateTime.atZone(zoneId).toInstant();
        return Date.from(instant);
    }

    /**
     * 将 localDate 转换为 Date
     */
    private Date localDateToDate(LocalDate localDate){
        ZoneId zoneId = ZoneId.systemDefault();
        Instant instant = localDate.atStartOfDay(zoneId).toInstant();
        return Date.from(instant);
    }

    /**
     * 将 localTime 转换为 Date
     */
    private Date localTimeToDate(LocalTime localTime){
        ZoneId zoneId = ZoneId.systemDefault();
        Instant instant = localTime.atDate(LocalDate.now()).atZone(zoneId).toInstant();
        return Date.from(instant);
    }
}
